﻿/**************************************************************
 *
 * 唯一标识：ca6cca04-784c-4b97-b722-316207a5c9d5
 * 命名空间：Sgr.UPMS.Application.Commands.Departments
 * 创建时间：2023/8/27 19:35:22
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：创建部门命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Queries;
using Sgr.Domain.Entities;
using Sgr.Exceptions;
using Sgr.UPMS.Domain.Departments;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Departments
{
    /// <summary>
    /// 创建部门命令处理器
    /// </summary>
    public class CreateDepartmentCommandHandle : IRequestHandler<CreateDepartmentCommand, bool>
    {
        private readonly IDepartmentRepository _departmentRepository;
        private readonly IDepartmentManage _departmentManage;
        private readonly ICurrentUser _currentUser;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository">部门仓储</param>
        /// <param name="departmentManage">部门管理器</param>
        /// <param name="currentUser"></param>
        public CreateDepartmentCommandHandle(IDepartmentRepository departmentRepository,
            IDepartmentManage departmentManage,
            ICurrentUser currentUser)
        {
            _departmentRepository = departmentRepository;
            _departmentManage = departmentManage;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 处理创建部门命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<bool> Handle(CreateDepartmentCommand request, CancellationToken cancellationToken)
        {
            long orgId = QueryHelper.GetOrgId(_currentUser);
            // 创建部门
            Department department = await _departmentManage.CreateNewAsync(
                request.Name,
                request.OrderNumber,
                request.State,
                request.Remarks,
                request.ManagerUserId,
                request.Leader,
                request.Phone,
                request.Email,
                orgId,
                request.ParentId,
                cancellationToken);

            department.MarkAsChanged();
            // 保存到仓储
            await _departmentRepository.InsertAsync(department, cancellationToken);

            return true;
        }
    }
}